import { StroageUtil } from "../../../vv/utils/StroageUtil";
import { stroageKey } from "../../constants";
import { testData } from "../testData";

export class ResourceItemBean {
    private static _inst: ResourceItemBean = null;
    public static get inst() {
        if (!this._inst) {
            this._inst = new ResourceItemBean();
        }
        return this._inst;
    }

    //设置缓存
    public setCache(id: number, obj: any) {
        if (!obj) {
            StroageUtil.removeItem(stroageKey.ResourceItemBean + "_" + id);
            return;
        }
        StroageUtil.setValue(stroageKey.ResourceItemBean + "_" + id, obj);
    }

    //获取缓存
    public getCache(id: number) {
        return StroageUtil.getObject(stroageKey.ResourceItemBean + "_" + id);
    }

    //清除缓存
    public cleanCache(id: number) {
        StroageUtil.removeItem(stroageKey.ResourceItemBean + "_" + id);
    }

    //删除某个资源并更新缓存
    public removeResource(mapId: number, rowId: number) {
        if (rowId == null) {
            return;
        }
        let data = this.getCache(mapId);
        if (data) {
            data = data.filter((x: any) => x.rowId !== rowId);
            this.setCache(mapId, data);
        }
    }

    /**
     * 更新地图刷新缓存
     * @param mapId
     * @param refreshTime
     */
    public updateResourceRefreshTimeCache(mapId: number, refreshTime: number) {
        let arr: Array<any> = StroageUtil.getObject(stroageKey.mapRefreshTime);
        let data = arr.map((x) => {
            if (x.mapId == mapId) {
                x.refreshTime = refreshTime;
            }
            return x;
        });
        StroageUtil.setValue(stroageKey.mapRefreshTime, data);
    }

    /**
     * 获取地图刷新时间
     * @param mapId
     */
    public getResourceRefreshTimeCache(mapId: number) {
        let data: Array<any> = StroageUtil.getObject(stroageKey.mapRefreshTime);
        if (data == null || data.length == 0) {
            data = testData.getResourceRefreshTime(mapId);
            let arr = data.map((x) => {
                x.waitTime = x.refreshTime;
                return x;
            });
            StroageUtil.setValue(stroageKey.mapRefreshTime, arr);
        }
        if (!data) {
            cc.log("找不到地图刷新时间缓存");
            return null;
        }
        return data.find((x: any) => x.mapId == mapId).refreshTime;
    }
}
